package com.li.service.impl;

import com.li.service.RedisLock01Service;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
@Slf4j
@Service
public class RedisLock01ServiceImpl implements RedisLock01Service {
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Value("${server.port}")
    private String port;
    private Lock lock = new ReentrantLock();
    @Override
    public String sale() {
        String retMessage="";
        try {
            lock.lock();
            //查询库存信息
            String result = redisTemplate.opsForValue().get("inventory");
            //判断库存是否足够
            Integer inventoryNum = result == null ? 0 : Integer.parseInt(result);
            if (inventoryNum > 0){
                redisTemplate.opsForValue().set("inventory",String.valueOf(inventoryNum-1));
                retMessage = "成功售出商品，当前库存为：" + redisTemplate.opsForValue().get("inventory") + "，购买端口为：" + port;
                System.out.println(retMessage);
            }else{
                retMessage = "库存不足，当前库存为：" + redisTemplate.opsForValue().get("inventory") + "，购买端口为：" + port;
                System.out.println(retMessage);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            lock.unlock();
        }
        return retMessage;
    }
}
